package com.czh.practice.server.config.interceptor;

import com.czh.practice.server.constants.UserConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Feign请求拦截器
 *
 * @author: ChickenWing
 * @date: 2023/12/3
 */
@Component
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(requestAttributes)){
            HttpServletRequest request = (HttpServletRequest) requestAttributes.getRequest();
            String loginId = request.getHeader(UserConstant.USER_CONTEXT_ID);
            if (StringUtils.isNotBlank(loginId)) {
                requestTemplate.header(UserConstant.USER_CONTEXT_ID, loginId);
                log.info("practice服务:feign拦截器添加了用户信息:{}", loginId);
            }else {
                log.warn("practice服务:feign拦截器没有找到用户信息");
            }
        }

    }

}
